
<template>
    <div>
        <div>
            <div class="categoryAddClass">

                <span style="margin-top: 10px;margin-right: 5px;">类别: </span>
                <div style="margin-top: 10px;display: flex;justify-content: left">
                <el-input v-model="productCategory"></el-input>
                <el-button icon="el-icon-plus" type="primary" @click="insertProductCategory()">新增类型</el-button>
                        <el-button icon="el-icon-plus" type="primary" @click="openDialog()">新增商品</el-button>
                </div>
            </div>

        </div>
        <!--新增或编辑打开dialog，补充需要展示的字段-->
        <div>
            <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" >
                <el-form :model="form" class="horizontal-form">
                    <el-row>
                        <!-- 双列布局 -->
                        <el-col :xs="24" :sm="12">
                            <el-form-item label="商品名称" >
                                <el-input v-model="form.productSpuName" autocomplete="off" style="width: 300px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12">
                            <el-form-item label="所属类别" >
                                <el-select v-model="form.productCategoryId" placeholder="请选择" style="width: 300px">
                                    <el-option
                                            v-for="item in options"
                                            :key="item.categoryId"
                                            :label="item.categoryName"
                                            :value="item.categoryId">
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!-- 双列布局 -->
                        <el-col :xs="24" :sm="12">
                            <el-form-item label="商品价格" >
                                <el-input v-model="form.productSkuPrice" autocomplete="off" style="width: 300px"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12">
                            <el-form-item label="商品描述" >
                                <el-input v-model="form.productSkuSpecs" autocomplete="off" style="width: 300px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                    <el-row>
                        <!-- 双列布局 -->
                        <el-col :xs="24" :sm="12">
                            <el-form-item label="商品图片" >
                                <el-upload
                                        class="upload-demo"
                                        drag
                                        action="/plateform/system/hr/data/upload"
                                        :headers="getToken()"
                                        :show-file-list="false"
                                        :before-upload="beforeAvatarUpload"
                                        :on-success="handleAvatarSuccess"
                                        v-loading="loading"
                                        element-loading-text="上传中，请稍后..."
                                        element-loading-spinner="el-icon-loading"
                                        element-loading-background="rgba(0, 0, 0, 0.8)"
                                >
                                    <img v-if="form.productSkuImage" :src="getImageSrc(form.productSkuImage)" class="product-image">
                                    <div v-else>
                                        <i class="el-icon-upload"></i>
                                        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                    </div>
                                </el-upload>
                            </el-form-item>
                        </el-col>
                        <el-col :xs="24" :sm="12">
                            <el-form-item label="库存数量" >
                                <el-input v-model="form.productSkuStock" autocomplete="off" style="width: 300px"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <div>
                        <el-button @click="closeDialog">取 消</el-button>
                        <el-button type="primary" @click="handlerSave">确 定</el-button>
                    </div>
                </div>
            </el-dialog>
        </div>
        <div class="product-container">

            <el-tabs v-model="activeCategory" type="card" @tab-click="handleTabClick">
                <el-tab-pane
                        v-for="category in categories"
                        :key="category"
                        :label="category"
                        :name="category">

                    <el-row class="product-row" :gutter="20">
                        <el-col :span="8" v-for="product in filteredProducts(category)" :key="product.productSpuId">
                            <el-card class="product-card">
                                <div class="image-container">

                                    <el-button class="floating-btn-edit"  type="text" icon="el-icon-edit"
                                               @click="openDialog(product)"></el-button>
                                    <el-button class="floating-btn-del"  type="text" icon="el-icon-delete"
                                               @click="deleteProduct(product)"></el-button>
                                    <img :src="getImageSrc(product.productSkuImage)" class="product-image" :alt="product.productSpuName">

                                </div>

                                <div class="product-info">
                                    <h3 class="product-name">{{ product.productSpuName }}</h3>
                                    <h3 class="product-stock">剩余库存：{{ product.productSkuStock }}</h3>
                                    <div class="product-action">
                                        <span class="product-price">¥{{ product.productSkuPrice }}</span>
                                        <div>
                                            <el-input-number
                                                    v-model="product.orderNum"
                                                    :min="1"
                                                    :max="10"
                                                    label="购买数量"
                                                    style="width: 100px;margin-right: 5px;"></el-input-number>
                                            <el-button class="add-to-cart-btn" type="primary" size="mini"
                                                       @click="orderCreate(product)">
                                                下订单
                                            </el-button>
                                        </div>
                                    </div>
                                </div>
                            </el-card>

                        </el-col>
                    </el-row>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>

</template>

<script>
    export default {
        name: 'SecGoods',
        data() {
            return {
                productCategory:'',
                activeCategory: '全部',
                dialogFormVisible: false,
                //  按照数据库要求保存字段信息
                form: {
                    productSpuId:'',
                    productSpuName:'',
                    productSkuPrice:'',
                    productSkuSpecs:'',
                    productSkuImage:'',
                    productSkuStock:'',
                    productCategoryName:'',
                    productCategoryId:'',
                    orderNum:''
                },
                token:'',
                filePath:'',
                loading:false,
                dialogTitle:'新增',
                products: [],
                options: [],
                goodRequest:{
                    goodId:'',
                    goodNum:''
                }



            }
        },
        mounted() {
            this.init();
        },
        computed: {
            categories() {
                const allCategories = this.products.map(p => p.productCategoryName)
                return ['全部', ...new Set(allCategories)]
            }
        },
        methods: {
            orderCreate(product) {
                this.goodRequest.goodId = product.productSpuId;
                this.goodRequest.goodNum = product.orderNum;
                //  完成订单的调用
                this.putRequest("/seckill/secorders/orders/createOrder",this.goodRequest).then(resp=>{
                    if(resp){
                        this.init();
                    }
                })
            },
            insertProductCategory(){
                this.getRequest("/seckill/secgoods/productCategory/insertProductCategory/?productCategory="+this.productCategory).then(resp=>{
                    if(resp){
                        this.productCategory='';
                        this.init();
                    }
                })
            },
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);
                this.form.productSkuImage = res.data;
                this.loading = false;
            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;
                this.loading = true;
                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                    this.loading = false;
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                    this.loading = false;
                }

                return isJPG && isLt2M;
            },
            getToken(){
                let str = window.sessionStorage.getItem("token");
                this.token = str;
                const authorization = this.token;
                return { "X-TOKEN":authorization }
            },
            getImageSrc(headUrl){
                if(headUrl.startsWith('http')){
                    return headUrl;
                }
                return this.filePath+"/"+headUrl;

            },
            deleteProduct(product){
                this.$confirm('此操作将永久删除['+product.productSpuName+'], 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    //   实现 删除 路径
                    this.deleteRequest("/seckill/secgoods/good/deleteGoodsById/"+product.productSpuId).then(resp=>{
                        if(resp){
                            this.init();
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            handlerSave(){
                if(this.dialogTitle=='新增'){
                    //   实现 新增 路径
                    this.postRequest("/seckill/secgoods/good/base/insertGood",this.form).then(resp=>{
                        if(resp){
                            this.dialogFormVisible = false;
                            this.init();
                        }
                    })
                }else{
                    //   实现 修改 路径
                    this.putRequest("/seckill/secgoods/good/base/updateGood",this.form).then(resp=>{
                        if(resp){
                            this.dialogFormVisible = false;
                            this.init();
                        }
                    })
                }
            },
            // 关闭新增或编辑dialog
            closeDialog(){
                this.dialogFormVisible = false;
            },
            //  为展示元素初始化赋值
            // 打开新增或编辑dialog
            openDialog(row){
                this.dialogFormVisible = true;
                if(row){
                    this.dialogTitle='编辑';
                    this.form.productSpuId=row.productSpuId;
                    this.form.productSpuName=row.productSpuName;
                    this.form.productSkuPrice=row.productSkuPrice;
                    this.form.productSkuSpecs=row.productSkuSpecs;
                    this.form.productSkuImage=row.productSkuImage;
                    this.form.productSkuStock=row.productSkuStock;
                    this.form.productCategoryName=row.productCategoryName;
                    this.form.productCategoryId=row.productCategoryId;
                    this.form.orderNum=row.orderNum;

                }else{
                    this.dialogTitle='新增';
                    this.form.productSpuId='';
                    this.form.productSpuName='';
                    this.form.productSkuPrice='';
                    this.form.productSkuSpecs='';
                    this.form.productSkuImage='';
                    this.form.productSkuStock='';
                    this.form.productCategoryName='';
                    this.form.productCategoryId='';
                    this.form.orderNum='';
                }

            },
            init(){
                this.getRequest("/seckill/secgoods/good/selectAllGoods").then(resp=>{
                    if(resp){
                        this.products = resp.data;

                    }
                });
                this.getRequest("/seckill/secgoods/productCategory/selectAllProductCategory").then(resp=>{
                    if(resp){
                        this.options = resp;

                    }
                });
                this.getRequest("/system/hr/getCommonFilePath").then(resp=>{
                    if(resp){
                        this.filePath = resp;
                    }
                })
            },

            filteredProducts(category) {
                return category === '全部'
                    ? this.products
                    : this.products.filter(p => p.productCategoryName === category)
            },
            handleTabClick(tab) {
                this.activeCategory = tab.name
            }
        }
    }
</script>

<style scoped>
    .categoryAddClass{
        display: flex;
        justify-content: flex-start;
        margin-bottom: 20px;
    }
    /* 基础水平布局 */
    .horizontal-form .el-form-item {
        display: flex;
        align-items: center;
    }
    .image-container {
        position: relative;
        height: 200px;
        margin: 0 auto;
    }
    .floating-btn-edit {
        position: absolute;
        z-index: 10;
        right: 40px;
        padding: 10px 0;
        color: blue;
    }
    .floating-btn-del {
        position: absolute;
        z-index: 10;
        right: 10px;
        padding: 10px 0;
        color: red;
    }

    .product-container {
        max-width: 1200px;
        margin: 20px auto;
        padding: 20px;
    }

    .page-title {
        text-align: center;
        margin-bottom: 30px;
    }

    .product-row {
        margin-bottom: 20px;
    }

    .product-card {
        margin-bottom: 20px;
        transition: transform 0.3s;
    }

    .product-card:hover {
        transform: translateY(-5px);
    }

    .product-card >>> .el-card__body {
        padding: 0;
    }

    .product-image {
        width: 100%;
        height: 100%;
        display: block;
        /*object-fit: cover;*/
    }

    .product-info {
        padding: 14px;
    }

    .product-name {
        margin: 0 0 10px 0;
        font-size: 16px;
    }
    .product-stock {
        margin: 0 0 10px 0;
        font-size: 12px;
    }

    .product-action {
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .product-price {
        color: #f56c6c;
        font-size: 18px;
        font-weight: bold;
    }

    .add-to-cart-btn {
        float: right;
    }

    /* 标签页样式增强 */
    .el-tabs >>> .el-tabs__item {
        font-size: 16px;
        padding: 0 20px;
    }

    .el-tabs >>> .el-tabs__nav-wrap::after {
        height: 1px;
    }
</style>
